/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.pojo.PPInventoryUpdateDto;
import me.zhengjie.pojo.PPWarningResp;
import me.zhengjie.pojo.Resp;
import me.zhengjie.pojo.sqlServer.PPInventory;
import me.zhengjie.ppService.SseService;
import me.zhengjie.repository.PPInventoryRepository;
import me.zhengjie.service.PPInventoryService;
import me.zhengjie.service.dto.PPInventoryDto;
import me.zhengjie.service.dto.PPInventoryQueryCriteria;
import me.zhengjie.service.dto.PPTimeConfigDto;
import me.zhengjie.utils.PageResult;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
* @website https://eladmin.vip
* @author xinglin
* @date 2024-08-19
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "pp库存管理")
@RequestMapping("/api/ppInventory")
public class PPInventoryController {

    private final PPInventoryService ppInventoryService;
    private final me.zhengjie.ppService.PPInventoryService doiminPPInventoryService;
    private final PPInventoryRepository ppInventoryRepository;
    private final SseService sseService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('ppInventory:list')")
    public void exportPpInventory(HttpServletResponse response, PPInventoryQueryCriteria criteria) throws IOException {
        ppInventoryService.download(ppInventoryService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询pp库存")
    @ApiOperation("查询pp库存")
    @PreAuthorize("@el.check('ppInventory:list')")
    public ResponseEntity<PageResult<PPInventoryDto>> queryPpInventory(PPInventoryQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(ppInventoryService.queryAll(criteria,pageable),HttpStatus.OK);
    }
//    public ResponseEntity<PageResult<PPInventoryUI>> queryPpInventory(PPInventoryQueryCriteria criteria, Pageable pageable){
//        return new ResponseEntity<>(ppInventoryService.queryAll(criteria,pageable),HttpStatus.OK);
//    }

    @PostMapping
    @Log("新增pp库存")
    @ApiOperation("新增pp库存")
    @PreAuthorize("@el.check('ppInventory:add')")
    public ResponseEntity<Object> createPpInventory(@Validated @RequestBody PPInventory resources){
        ppInventoryService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改pp库存")
    @ApiOperation("修改pp库存")
    @PreAuthorize("@el.check('ppInventory:edit')")
    public ResponseEntity<Object> updatePpInventory(@Validated @RequestBody PPInventory resources){
        ppInventoryService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除pp库存")
    @ApiOperation("删除pp库存")
    @PreAuthorize("@el.check('ppInventory:del')")
    public ResponseEntity<Object> deletePpInventory(@RequestBody Integer[] ids) {
        ppInventoryService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }


//    @PostMapping(value = "/addPPInventory")
//    @Log("新增库存")
//    @ApiOperation("新增库存")
//    @PreAuthorize("@el.check('ppInventory:add')")
//    public Resp addPPInventory(@RequestBody InBoundInfo inBoundInfo){
//
//        ppInventoryService1.savePPInventory();
//
//    }

    @PutMapping("/updatePPInventory")
    @Log("更新pp库存信息")
    @ApiOperation("更新pp库存信息")
//    @PreAuthorize("@el.check('ppInventory:edit')")
    public Resp updatePPInventory(@RequestBody PPInventoryUpdateDto ppInventoryUpdateDto){
        try{
            ppInventoryService.updateByIdAndQty(ppInventoryUpdateDto);
             return Resp.builder()
                     .msg("更新成功")
                     .status(200)
                     .build();

        }catch (Exception e){
            return Resp.builder()
                    .msg("更新失败")
                    .status(500)
                    .build();
        }
    }


    @GetMapping(value = "/getWarningPPInventory",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @Log("获取pp状态不为safe的pp库存")
    @ApiOperation("获取pp状态不为safe的pp库存")
    public SseEmitter getWarningPPInventory(HttpServletResponse response) {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        response.addHeader("Content-Type", "text/event-stream");
        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("X-Accel-Buffering", "no");

        String ip = request.getRemoteAddr() + ":" + request.getRemotePort();
        SseEmitter sseEmitter = sseService.connect(ip);
        try {
            sseEmitter.send(SseEmitter.event().comment("异常物料推送"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return sseEmitter;
    }


    @DeleteMapping("/deletePPInventory/{id}")
    @Log("通过id删除pp库存")
    @ApiOperation("通过id删除pp库存")
//    @PreAuthorize("@el.check('ppInventory:del')")
    public Resp deletePpInventory(@PathVariable Integer id) {
        try {
            ppInventoryService.deleteById(id);
            return Resp.builder()
                    .msg("删除成功")
                    .status(200)
                    .build();
        }catch (Exception e){
            return Resp.builder()
                    .msg("删除失败")
                    .status(500)
                    .build();
        }

    }


    /**
     * 根据库存ip获取pp库存信息
     * @return
     */
    @GetMapping("/get/{id}")
    public PPInventory get(@PathVariable Integer id){
        return ppInventoryRepository.findById(id).orElse(null);
    }


    @PostMapping("/deleteInventory/{palletCode}")
    public Resp test(@PathVariable String palletCode) {
        try{
            ppInventoryService.deleteByPalletCode(palletCode);

            return Resp.builder()
                    .msg("删除成功")
                    .status(200)
                    .build();

        }catch (Exception e){

            return Resp.builder()
                    .msg("删除失败")
                    .status(500)
                    .build();

        }
    }

    /**
     * 更新pp时间配置
     * @param ppTimeConfigDto
     * @return
     */
    @PutMapping("/updatePPTimeConfig")
    public Resp updatePPTimeConfig(@RequestBody PPTimeConfigDto ppTimeConfigDto){
        try{
            doiminPPInventoryService.updatePPTimeConfig(ppTimeConfigDto);
            return Resp.builder()
                    .msg("更新成功")
                    .status(200)
                    .build();
        }catch (Exception e){
            return Resp.builder()
                    .msg("更新失败")
                    .status(500)
                    .build();
        }
    }


    //人工出库
    @PostMapping("/manualOutbound/{id}")
    public Resp manualOutbound(@PathVariable Integer id){
        try{
            doiminPPInventoryService.manualOutbound(id);
            return Resp.builder()
                    .msg("人工出库成功")
                    .status(200)
                    .build();
        }catch (Exception e){
            return Resp.builder()
                    .msg("手动出库失败")
                    .status(500)
                    .build();
        }
    }




}